package cn.kgc.controller;

import cn.kgc.config.WxConfig;
import cn.kgc.dto.Dto;
import cn.kgc.dto.DtoUtil;
import cn.kgc.exception.UserErrorCode;
import cn.kgc.service.WxService;
import cn.kgc.utils.BaseException;
import cn.kgc.utils.HttpclientUtils;
import cn.kgc.utils.IErrorCode;
import cn.kgc.utils.UrlUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Slf4j
public class WxController {


    @Autowired
    WxConfig wxConfig;



    @Autowired
    WxService dmLoginService;

    /**
     * 重定向到微信的扫一扫界面
     * @return
     */
    @RequestMapping("/p/vendors/wechat/login")
    public void wxLogin(HttpServletResponse httpServletResponse) throws IOException {

        StringBuffer urlStringBuffer=new StringBuffer("https://open.weixin.qq.com/connect/qrconnect?appid=");
        urlStringBuffer.append(wxConfig.getAppid());
        urlStringBuffer.append("&redirect_uri=");
        urlStringBuffer.append(URLEncoder.encode("http://localhost:8160/api/callback"));
        urlStringBuffer.append("&response_type=code&scope=snsapi_login&state=dm#wechat_redirect");


        String url=urlStringBuffer.toString();
        httpServletResponse.sendRedirect(url);
    }

    /**
     * 给微信平台回调的接口，一旦用户授权登录，微信平台就调用此接口
     * @param code
     * @param state
     * @return
     * @throws Exception
     */
    @RequestMapping("/callback")
    public Dto loginCallback(String code,String state) throws Exception {
        log.info("微信回调code:{},state:{}",code,state);
        if(state!=null&&!state.equals("dm")){
            throw new BaseException(UserErrorCode.INVLIDE_REQ);
        }

        System.out.println(code);
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        StringBuffer stringBuffer=new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        stringBuffer.append(wxConfig.getAppid());
        stringBuffer.append("&secret=");
        stringBuffer.append(wxConfig.getSecret());
        stringBuffer.append("&code=");
        stringBuffer.append(code);
        stringBuffer.append("&grant_type=authorization_code");
        //发送http请求的工具类
//        String response=HttpClientUtil.doGet(stringBuffer.toString());
        //代码工具类封装了一个http请求的客户端，发送http请求，json
        String json = UrlUtils.loadURL(stringBuffer.toString());
        /*{
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }*/
        System.out.println(json);
        Map<String, Object> map = new HashMap<>();
        //json格式数据转为Map
        Map tokenMap = JSON.parseObject(json, Map.class);
        String access_token = tokenMap.get("access_token").toString();
        String openId = tokenMap.get("openid").toString();
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        StringBuilder userInfoUrl = new StringBuilder("https://api.weixin.qq.com/sns/userinfo");
        userInfoUrl.append("?access_token=" + access_token);
        userInfoUrl.append("&openid="+openId);
        //发送请求获取用户信息
        String userInfoJson = UrlUtils.loadURL(userInfoUrl.toString());
        System.out.println(userInfoJson);
        Map<String, Object> userInfoMap = new HashMap<String, Object>();
        userInfoMap = JSON.parseObject(userInfoJson, Map.class);
        //实现自身的业务：
//                1.用户信息入库
//                2.获取用户的头像
//                3.生成token
//                4.将用户信息缓存到redis里面  token  dmUserVo
        String token = dmLoginService.wechatLogin(userInfoMap, openId);
        return DtoUtil.returnDataSuccess(token);
    }



}
